<template>
  <div class="confirm-modal-box month-modal medical-waste">
    <div class="condition-filter-box">
      <button :class="['button',todayActive ? 'btn-active' : '']" @click="checkToday('clear')">今日</button>
      <el-date-picker
          v-model="pickDate"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期" 
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          @change="searchDate"
      />
      <button class="button" style="width:148px;" @click="showModal">{{tipsText}}科室过滤</button>
      <el-button v-if="exportLimit != '1'" type="primary" class="primary-btn" @click="exportExcel">导出</el-button>
      <el-button v-else class="primary-btn" type="primary" @click="showTips" :disabled="isExporting">导出</el-button>

      <el-popover
          placement="bottom"
          width="400"
          popper-class="popover-card"
          trigger="click">
          <el-card shadow="never">
            <div slot="header">时间分割设置</div>
            <div>
              <div>
                <el-time-picker format="HH:mm" value-format="HH:mm" v-model="hw_noon_point" placeholder="请选择" @change="saveTime"></el-time-picker>
                <!-- <common-switch v-model="hw_noon_switch" name="noon_switch" @change="saveSwitch"></common-switch> -->
                <el-switch 
                    :width="60" 
                    v-model="hw_noon_switch" 
                    active-value="1"
                    inactive-value="0"
                    active-color="#13ce66"
                    @change="saveSwitch">
                </el-switch>
              </div>
              <div class="footer">
                <span class="red">*若开启，则一天分开2次统计</span>
              </div>
            </div>
          </el-card>
          <button class="button" slot="reference">时间分割设置</button>
        </el-popover>
    </div>

    <transition name="fade">
        <div class="result-tips" v-if="!isLoading && newTableData.length > 0">
            <h3>
                <span>当前搜索结果为</span>
                <span>{{pickDate[0]}} 至 {{pickDate[1]}}</span>
                <span>{{ksText}}</span>
                <span>数据</span>
            </h3>
        </div>
    </transition>

    <div class="no-info-tips" v-if="!isLoading && newTableData.length == 0">
        <p>暂无数据</p>
    </div>
    <div 
      class="loading-tips" 
      v-if="isLoading" 
      v-loading="isLoading"
      element-loading-text="拼命加载中..."
      element-loading-background="rgba(255, 255, 255, 0.5)">
    </div>
    <el-table
        border
        v-if="!isLoading && newTableData.length > 0 && tableCol.length > 0"
        :cell-style="cellStyle"
        :header-cell-style="cellStyle"
        :data="newTableData"
        :span-method="objectSpanMethod"
        :show-summary="hw_noon_switch === '1' ? false : true"
        :summary-method="getSummaries">
        <el-table-column
            prop="date"
            label="日期"
            align="center"
            width="140">
        </el-table-column>
        <el-table-column
            prop="time"
            label="时间"
            align="center"
            v-if="hw_noon_switch === '1'"
            width="140">
        </el-table-column>
        <el-table-column
            v-for="item in tableCol"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            align="center"
            width="100">
            <div>
              <el-table-column
              v-for="(val, idx) in item.sub"
              :key="idx"
              align="center"
              :label="val.label"
              :prop="val.prop"
              width="100">
              <template slot-scope="scope">
                <span>{{scope.row[val.prop]}}</span>
              </template>
            </el-table-column>
            </div>
        </el-table-column>
        <el-table-column
          label="交接双方签名"
          align="center"
        >
          <el-table-column
              header-align="center"
              align="center"
              prop="step1_uname"
              label="交送人"
              width="100">
              <template slot-scope="scope">
                  <div class="custom-item">
                      <div class="info">
                          <span>{{scope.row.step1_uinfo ? scope.row.step1_uinfo : scope.row.step1_uname}}</span>
                          <div v-if="scope.row.step1_sign">
                              <img :src="scope.row.step1_sign" alt="" @click="showSign(scope.$index, scope.row, scope.row.step1_sign)" style="width: 25px;vertical-align: middle;">
                          </div>
                      </div>
                      <div class="icons" v-if="scope.row.date !== '总计'" @click="showDetails(scope)">
                          <span class="more-icon">...</span>
                      </div>
                  </div>
              </template>
          </el-table-column>
          <el-table-column
              header-align="center"
              align="center"
              prop="uname"
              label="收运称重"
              width="100">
          </el-table-column>
        </el-table-column>
    </el-table>

    <el-dialog custom-class="select-ks-dialog" title="可选择的科室" append-to-body :visible.sync="isModal" :show-close="false" center @close="postAllData">
        <div class="content">
            <div class="search">
                <el-input type="text" v-model="searchText" clearable placeholder="请输入内容，可按Enter搜索" @keyup.enter.native="searchKs"/>
                <button class="search-btn button" @click="searchKs">搜索</button>
            </div>
            <div class="list">
                <ul>
                    <li v-for="(item, index) in ksList" :key="index" @click="chooseKs(item.department)">
                        <span>{{item.department}}</span>
                        <i v-if="item.isChoosed" class="el-icon-circle-check"></i>
                    </li>
                </ul>
            </div>
        </div>
    </el-dialog>

    <el-dialog
        title=""
        :visible.sync="isShowSign"
        :modal="false"
        append-to-body
        :custom-class="'sign-pic-dialog'"
        :show-close="false">
        <div class="img-box">
            <img :src="currSignPic" alt="">
        </div>
    </el-dialog>

    <el-dialog
        width="80%"
        :visible.sync="isShowModal"
        :custom-class="'table-modal'"
        append-to-body
        :show-close="false">
        <DataTable 
          v-loading="isModalTableLoading"
          element-loading-text="加载中..."
          element-loading-background="rgba(255, 255, 255, 0.5)" 
          :data="currData" 
          :restData="restData" 
          :tag="'singleKs'" 
          @showSign="showSign">
        </DataTable>
    </el-dialog>


    <SignModal
        v-if="signVisible"
        :signType="'multiple'"
        :orders="undoTableData"
        @sure="handleSureSuccess"
        @handleCancel="switchSignModal"
    />

    <el-dialog
        :title="orderLis.title"
        :visible.sync="orderShow"
        :modal-append-to-body="false"
        width="90%">
        <WasteLis
            :order="orderLis"
        ></WasteLis>
    </el-dialog>

    <div class="v-mask" v-if="canShowTips" @click="hideTips"></div>
    <ExportWarmTips 
      v-if="canShowTips"
      :data="undoTableData" 
      :day="getDateText"
      @handle-jump="switchDayLis"
      @handle-close="hideTips">
      <div class="export-btn">
          <el-button type="primary" class="primary-btn" @click="exportExcel">立即导出</el-button>
      </div>
    </ExportWarmTips>
    
    <BatchHandover
      :show="canShowDayLis"
      :data="undoTableData"
      :col="colL"
      :day-lis="dayLis"
      :date="showDate"
      :export-day="getDateText"
      @handle-show-lis="switchDayLis"
      @handle-show-sign="switchSignModal"
      @handle-show-confirm="handleShowConfirm"
      @handle-show-classify-order="handleShowClassifyOrder"
    ></BatchHandover>

    <el-dialog
        title="医废确认"
        :visible.sync="confirmShow"
        :modal-append-to-body="false"
        width="740px">
        <HandConfirm
            v-if="confirmShow"
            :order="confirmOrder"
            :show-time="showDate"
            @sure="handleSureSuccess"
            @show-order="handleShowClassifyOrder"
        ></HandConfirm>
    </el-dialog>
  </div>
</template>

<script>
import today from '../../common/today'
import cookie from '../../common/cookie'
import { getHconfLisUrl, wastecategoryUrl, postHconfModUrl, wasteDetailsUrl, getAloneKsUrl, getAloneKsTwiceUrl, getDepartmentMyInfoUrl } from '../../common/ajax'
import { CONFIRM_LIS, STATUS_LIS } from '../../constants/index.js'
import DataTable from './data-table'
import ExportWarmTips from './export-warm-tips'
import BatchHandover from './batch-handover'
import WasteLis from './sub/WasteLis';
import HandConfirm from './sub/HandConfirm';
import SignModal from './sign-modal';
import qs from "qs"
import axios from "axios"
export default {
  data(){
    return{
      pickerOptions: {   // 禁选当天之后的日期
          disabledDate(date) {
              return date.getTime() > Date.now();
          }
      },
      dataList: [],
      pickDate: [],   // 日期选择
      allData: [],
      todayActive: false,
      isExporting: false,
      tableCol: [],
      newTableData: [],
      cellStyle: ({row, column, rowIndex, columnIndex}) => {  // 动态改变指定列样式
          if(column.label.indexOf('数量') != -1 || column.label.indexOf('重量') != -1){
            if(column.property.indexOf('Total') == -1){
              let id = column.label.indexOf('数量') != -1 ? column.property.substr(3) : column.property.substr(6)
              return `background:${this.tableCol.find(v => v.id === id).colour} !important`
            }
          }else if(Number(column.property)){  // 关于一级表头的样式
            return `background:${this.tableCol.find(v => v.id === column.property).colour} !important`
          }
          return ''
      },
      // 可选择科室
      tipsText: '添加',
      searchText: '',
      ksList: [],
      isModal: false,
      ksText: '',
      // 签名图
      isShowSign: false,
      currSignPic: '',
      // 交接单modal
      isShowModal: false,
      currData: [],
      orderInfo: [],
      restData: [],
      // 开关
      isHandleOver: '0',
      hw_noon_point: '',
      hw_noon_switch: '0',
      isLoading: false,
      canShowResultTips: false,
      isModalTableLoading: false,
      // 导出前的交接检测
      showDate:{day:'',time:''},
      checkType: [],   // 存放指定要查看的医废类型
      canShowDayLis: false,
      canShowTips: false,
      colL:[
          {title:'时间',width:''},
          {title:'类型',width:''},
          {title:'数量',width:''},
          {title:'重量',width:''},
          {title:'收运称重人',width:''},
          {title:'状态',width:''}
      ],
      orderLis:{},
      orderShow:false,
      confirmOrder:{},
      confirmShow:false,
      currOrders: [],  // 待导出数组
      exportDay: '',
      dayLis: {
          data: [],
          types: [
              // { namewc: '感染性', totals: '100' }
          ]
      },
      undoTableData: [],
      signVisible: false,
      isExporting: false,
      exportLimit: '',
    }
  },
  created() {
    this.getHconfData();
  },
  components:{
    DataTable,
    ExportWarmTips,
    BatchHandover,
    WasteLis,
    HandConfirm,
    SignModal,
  },
  computed: {
    getDateText(){
      return `${this.pickDate[0]}${`${this.pickDate[0] != this.pickDate[1] ? ` 至 ${this.pickDate[1]}` : ''}`}`
    }
  },
  methods: {
    handleSureSuccess(type,order){
        //二次确认成功后的操作
        this.confirmShow = false;
        this.postAllData()
        // if(type == 1){
        //     this.handleGetLis(0, order)
        // }else {
        //     this.handleGetLis(1, order);
        // }
    },
    //点击显示同类型的单
    handleShowClassifyOrder(order){
      if(order.lis.length == 0) return;  // 数量为0时不可点击查看
      this.orderLis = order;
      this.orderShow = true
    },
    //点击待交接
    handleShowConfirm(val){ //显示确认
        // if(val.title == '已交接' || val.staff.length == 0) return;
        this.confirmOrder = val;
        this.confirmShow = true;
        // this.isShowFill = true;
    },
    switchSignModal(){
        this.signVisible = !this.signVisible;
    },
    switchDayLis(){
        this.hideTips();
        this.canShowDayLis = !this.canShowDayLis
    },
    hideTips(isExporting){
        if(typeof(isExporting) == 'boolean') this.isExporting = isExporting;
        this.canShowTips = false;
    },
    showTips(){    //
        if(this.newTableData.length == 0) {
            throwErrorTips('暂无数据','')
            return;
        }
        this.canShowTips = true;
    },
    initData(){
      this.checkToday()
      this.searchKs()
      this.getHandleOver();
    },
    getHconfData(){
      jQuery.ajax({
        url: getHconfLisUrl,
        type: 'GET',
        success: res => {
          if(res.success){
            this.hw_noon_point = res.data.hw_noon_point.substring(0, res.data.hw_noon_point.length-3);
            this.hw_noon_switch = res.data.hw_noon_switch;
            this.exportLimit = res.data.hw_export_limit
            this.getTypeData();
          }
        }
      })
    },
    saveSwitch(value){
      this.hw_noon_switch = value;
      this.saveHconfData()
    },
    saveTime(val){
      this.hw_noon_point = val;
      this.saveHconfData()
    },
    saveHconfData(){
      this.isLoading = true;
      jQuery.ajax({
        url: postHconfModUrl,
        type: 'POST',
        data: JSON.stringify({
          hw_noon_point: this.hw_noon_point,
          hw_noon_switch: this.hw_noon_switch
        }),
        success: res => {
          if(res.success){
            this.$Message({type:'success',message:'修改成功！'});
            this.isLoading = false;
            this.postAllData();
          }else{
            throwErrorTips('修改失败',res.msg)
          }
        }
      })
    },
    getTypeData(){
      jQuery.ajax({
        url: wastecategoryUrl,
        type: 'GET',
        success: res => {
          if(res.success){
            this.dataList = res.data;
            this.checkType = this.dataList.map(v => v.id)
            this.initData();
          }
        }
      })
    },
    searchDate(item){
        this.pickDate = item;
        let _today = today.otherTime(new Date())
        if(this.pickDate.length == 0 || (this.pickDate[0] == _today && this.pickDate[1] == _today)) {
            this.checkToday()
            return;
        }else{
            this.postAllData()
        }
        
        if(this.todayActive) this.todayActive = false
    },
    getHandleOver(){
        this.isHandleOver = cookie.get('hw_handover_display')
    },
    showSign(index, item, image){
        this.isShowSign = true;
        this.currSignPic = image;
    },
    showDetails(scope){
          let form = {
            place: this.ksText
          }
          if(this.hw_noon_switch === '1'){
            Object.assign(form, {
              st: `${scope.row.date} ${scope.row.time.split('-')[0]}:00`,
              et: `${scope.row.date} ${scope.row.time.split('-')[1]}:59`,
            })
          }else{
            this.currData = this.allData.find(v => v.key == scope.row.date)
            Object.assign(form, {
                st: this.currData.key,
                et: this.currData.key,
                filter_ks: [],
                cs: this.dataList.filter(v => v.hang == 0).map(v2 => v2.id),
                shm: '',
                ehm: ''
            })
          }
          
          this.orderInfo  = []
          this.currData = []
          this.restData = []
          this.isShowModal = true;
          this.isModalTableLoading = true;
          jQuery.ajax({
            url: wasteDetailsUrl,
            type: 'POST',
            data: JSON.stringify(form),
            success: res => {
              this.orderInfo = res.data;
              if(res.data.length > 0) this.processData()

              const maxLimit = 100;
              this.currData = this.orderInfo.filter((v,i) => i < maxLimit);
              this.restData = this.orderInfo.filter((v,i) => i >= maxLimit);

              this.isModalTableLoading = false;
            }
          })
        },
    processData(){
        this.orderInfo.forEach(v => {
            v.weight += 'kg';
            v.subweight += 'kg';
            let status = '', step1_method = '', step2_method = '';
            status = STATUS_LIS[v.step];
            step1_method = v.step != 0 && v.step1_way ? CONFIRM_LIS[v.step1_way] : '';
            step2_method = v.step == 2 && v.step2_way ? CONFIRM_LIS[v.step2_way] : '';
            if(v.step2_time != '' && v.step1_time == ''){
                status = '已出库';
                step2_method = '已确认出库';
            }
            Object.assign(v, {
                status: status,
                step1_method: step1_method,
                step2_method: step2_method
            })
        })
    },
    getSummaries(param){
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if(index === 0){
          sums[index] = '总计';
          return;
        }
        if(index > this.tableCol.length * 2){
          sums[index] = '';
          return;
        }
        if(index % 2 !== 0){
          const values = data.map(item => {
              return Number(item[`num${index === this.tableCol.length * 2 ? 'Total' : `${column.property}`.substr(3)}`])
          });
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
                return prev + curr;
            } else {
                return prev;
            }
          }, 0);
        }else{
          const weights = data.map(item => {
              return Number(item[`weight${`${column.property}`.substr(6)}`])
          });
          let wts = weights.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                  return prev + curr;
              } else {
                  return prev;
              }
          }, 0);
          wts = parseFloat(wts).toFixed(2)
          sums[index] = `${wts}`;
        }
      })
      return sums;
    },
    chooseKs(item){
        this.ksText = item;
        this.checkActive();
        this.tipsText = '已添加'
    },
    hideModal(){
      this.isModal = false;
      this.postAllData();
    },
    searchKs(){
      jQuery.ajax({
        url: getDepartmentMyInfoUrl,
        type: 'GET',
        success: res => {
          this.ksList = res.data.map(v => Object.assign(v, {isChoosed: false}));
          if(this.ksText != '') this.checkActive()
          if(!this.isModal) this.postAllData();
        }
      })
    },
    checkActive(){
        this.ksList.forEach(v => {
            v.isChoosed = this.ksText == v.department ? true : false
        })
    },
    checkToday(text){
        if(text == 'clear') this.pickDate = []
        this.pickDate = [today.otherTime(new Date()), today.otherTime(new Date())]
        this.postAllData()
        this.todayActive = true
    },
    showModal(){
        this.isModal = true;
    },
    getNewTableData(){
        let arr = []
        this.allData.forEach(v => {
          v.vals.forEach(v2 => {
              if(arr.indexOf(v2.idwc) == -1) arr.push(v2.idwc)
          })
        })
        if(this.hw_noon_switch === '1'){
          let data = this.allData[this.allData.length-1]
          arr.forEach((v2, i2) => {
              Object.assign(data, {
                  [`num${v2}`]: data.wc_sum[i2].sum_num,
                  [`weight${v2}`]: data.wc_sum[i2].sum_weight,
              })
          })
        }
        if(this.hw_noon_switch === '1'){
          this.allData.forEach((v, i) => {
            if(i < this.allData.length - 1){
              let obj = {
                  date: v.key,
                  uname: v.uname,
                  numTotal: 0,
                  weightTotal: 0,
                  step1_uname: v.step1_uname == '' ? '暂无' : v.step1_uname,
                  step1_sign: v.step1_sign == '' ? '' : v.step1_sign,
                  step1_uinfo:  v.step1_uinfo,
                  time: v.time ? v.time.split(' ')[1] : ''
              }

              arr.forEach(v2 => { // 初始化所有曾出现过的类型的数量和重量
                  Object.assign(obj, {
                      [`num${v2}`]: 0,
                      [`weight${v2}`]: 0.00
                  })
              })

              v.vals.forEach(v2 => {
                  obj.numTotal = obj.numTotal + parseFloat(v2.num)
                  if(v2.total){
                    obj.weightTotal =  parseFloat(parseFloat(obj.weightTotal) + parseFloat(v2.total)).toFixed(2)
                  }
                  
                  Object.assign(obj, {
                      [`num${v2.idwc}`]: v2.num,
                      [`weight${v2.idwc}`]: v2.total ? parseFloat(v2.total).toFixed(2) : "0.00",
                  })
              })

              this.newTableData.push(obj)
            }else{
              this.newTableData.push(v)
            }
          })
        }else{
          this.allData.forEach((v, i) => {
            let obj = {
                date: v.key,
                uname: v.uname,
                numTotal: 0,
                weightTotal: 0,
                step1_uname: v.step1_uname == '' ? '暂无' : v.step1_uname,
                step1_sign: v.step1_sign == '' ? '' : v.step1_sign,
                step1_uinfo:  v.step1_uinfo,
                time: v.time ? v.time.split(' ')[1] : ''
            }

            arr.forEach(v2 => { // 初始化所有曾出现过的类型的数量和重量
                Object.assign(obj, {
                    [`num${v2}`]: 0,
                    [`weight${v2}`]: 0.00
                })
            })

            v.vals.forEach(v2 => {
                obj.numTotal = obj.numTotal + parseFloat(v2.num)
                if(v2.total) {
                  obj.weightTotal = parseFloat(parseFloat(obj.weightTotal) + parseFloat(v2.total)).toFixed(2)
                }
                Object.assign(obj, {
                    [`num${v2.idwc}`]: v2.num,
                    [`weight${v2.idwc}`]: v2.total ? parseFloat(v2.total).toFixed(2) : "0.00",
                })
            })

            this.newTableData.push(obj)
          })
        }
    },
    getTableCol(){
        let arr = []
        this.allData.forEach(v => {
            v.vals.forEach(v2 => {
                if(arr.indexOf(v2.idwc) == -1) arr.push(v2.idwc)
            })
        })
        arr.forEach(v => {
            this.tableCol.push({
                prop: this.dataList.find(v2 => v == v2.id).id,
                label: this.dataList.find(v2 => v == v2.id).name,
                colour: this.dataList.find(v2 => v == v2.id).colour,
                id: this.dataList.find(v2 => v == v2.id).id,
                sub: [
                  { label: '重量(kg)', prop: `weight${v}` },
                  { label: '数量', prop: `num${v}` },
                ]
            })
        })
        this.tableCol.push({
          prop: 'total',
          label: '合计',
          colour: '',
          id: 0,
          sub: [
            { label: '重量(kg)', prop: 'weightTotal' },
            { label: '数量', prop: 'numTotal' },
          ]
        })
    },
    resetData(){
        this.allData = [];
        this.tableCol = [];
        this.newTableData = [];
    },
    generateUndo(data){
        this.undoTableData = []
        // 生成所有日期
        let all_date = this.getAllDate()

        let types = []
        this.dataList.forEach(v => {
            types.push({
                color: v.colour,
                title: v.name
            })
        })

        // 多一层日期匹配判断
        for(let d of all_date){
            // 筛选出符合当前日期的单
            let tmpData = data.filter(v => v.ctime.split(' ')[0] == d)

            // 生成所有科室
            let all_ks = Array.from(new Set(tmpData.map(v => v.place)))

            let amlis1 = {date:d,title:'点击交接',name:'待交接',time:'00:00-12:59',staff:[],typeL:[],ks:[],types:types},
                pmlis1 = {date:d,title:'点击交接',name:'待交接',time:'13:00-23:59',staff:[],typeL:[],ks:[],types:types},
                amtypeL = [], pmtypeL = [],
                amks = [], pmks = [];

            for(var typeo of types){
                let o = typeo;
                o['lis'] = [];
                o['weight'] = 0;
                o['num'] = 0;
                o = JSON.stringify(o);
                amtypeL.push(JSON.parse(o));
                pmtypeL.push(JSON.parse(o));
            }
            for(var k of all_ks){
                let o = {ks:k};
                o['lis'] = [];
                o['weight'] = 0;
                o['num'] = 0;
                amks.push(o);
                pmks.push(o);
            }
            for(var od of tmpData){
                if(od.step == 0){
                    if(od.ctime.split(' ')[1] >= '00:00' && od.ctime.split(' ')[1] <= '12:59:59'){
                        amlis1.staff.push(od.uname)
                        for(let ty of amtypeL){
                            if(ty.title == od.namewc){
                                ty.lis.push(od);
                                ty.weight += Number(od.weight);
                                ty.num += Number(od.num)
                            }
                        }
                        let ind = all_ks.indexOf(od.place);
                        if(ind != -1){
                            amks[ind].lis.push(od);
                            amks[ind].weight += Number(od.weight);
                            amks[ind].num += Number(od.num)
                        }
                    }else if(od.ctime.split(' ')[1] >= '13:00' && od.ctime.split(' ')[1] <= '23:59:59'){
                        pmlis1.staff.push(od.uname)
                        for(let ty of pmtypeL){
                            if(ty.title == od.namewc){
                                ty.lis.push(od);
                                ty.weight += Number(od.weight);
                                ty.num += Number(od.num)
                            }
                        }
                        let ind = all_ks.indexOf(od.place);
                        if(ind != -1){
                            pmks[ind].lis.push(od);
                            pmks[ind].weight += Number(od.weight);
                            pmks[ind].num += Number(od.num)
                        }
                    }
                }
            }
            amlis1.staff = Array.from(new Set(amlis1.staff))
            pmlis1.staff = Array.from(new Set(pmlis1.staff))
            amlis1.ks = amks;
            pmlis1.ks = pmks;
            amtypeL.forEach((value,ind)=>{
                if(value.lis.length > 0){
                    amlis1.typeL.push(value)
                }
            })
            pmtypeL.forEach((value,ind)=>{
                if(value.lis.length > 0){
                    pmlis1.typeL.push(value)
                }
            })
            if(amlis1.typeL.length > 0){
                this.undoTableData.push(amlis1)
            }
            if(pmlis1.typeL.length > 0){
                this.undoTableData.push(pmlis1)
            }
        }

        if(this.undoTableData.length == 0 && this.canShowDayLis){  // 判断当前是否有未交接数据，如没有，则直接弹窗，提示可以导出上次选的时间
            this.canShowDayLis = false;
            this.canShowTips = true;
        }

        
        console.log('getUndoLis...');
        console.log(this.undoTableData);
    },
    getDayLis(data){
      this.dayLis = {
          data: [],
          types: []
      },
      this.dayLis.data = data.filter(v => v.step == 0)
      let arr = Array.from(new Set(data.map(v => v.namewc)))
      arr.forEach(v => {
          let obj = {
              namewc: v,
              totals: 0
          }
          obj.totals = this.dayLis.data.filter(v2 => v2.namewc == v).length
          this.dayLis.types.push(obj)
      })
    },
    getAllDate(){
        console.log(this.date, this.pickDate);
        let arr = []
        let curr = new Date(this.pickDate[0]).getTime()
        let last = new Date(this.pickDate[1]).getTime()
        while(curr <= last){
            arr.push(this.formatTime(new Date(curr)))
            curr += 1000 * 60 * 60 * 24
        }
        return arr;
    },
    formatTime(date){
        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()
        const hour = date.getHours()
        const minute = date.getMinutes()
        const second = date.getSeconds()

        // return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
        return [year, month, day].map(this.formatNumber).join('-')
    },
    formatNumber(n) {
        n = n.toString()
        return n[1] ? n : '0' + n
    },
    postUndoData(){
      let form = {
          st: this.pickDate[0] == '' ? '2021-12-22' : this.pickDate[0],
          et: this.pickDate[1] == '' ? '2021-12-22' : this.pickDate[1],
          filter_ks: [],
          cs: this.checkType,
          shm: '',
          ehm: '',
          filter_my_ks: true, // true查当前绑定的所有科室的全部单，false查全部科室的全部单
          filter_step_in: [0],  // 点击显示已交接时，如只要已交接1，则[1]，如没有点击，则[]
          // filter_step: 1
          page_index: 1,  // 按月查询不分页，所以默认1
          page_size: 9999,   // 用于获取指定范围所有未交接，将size设置9999
          opt: 1
      }

      // 获取后，过滤出该选中科室的数据
      jQuery.ajax({
        type: 'POST',
        url: wasteDetailsUrl,
        dataType: 'json',
        contentType: 'application/json;charset=UTF-8',
        data: JSON.stringify(form),
        success: function(res){
          if(res.success){
            this.undoTableData = []
            if(res.data.lis.length > 0) {
                this.getDayLis(res.data.lis)
                this.generateUndo(res.data.lis)
            }
          }else{
            throwErrorTips('',res.msg)
          }
        }.bind(this)
      })
      
      console.log(form);
    },
    postAllData(){
      if(this.ksText == '' && this.ksList.length != 0) {
        this.chooseKs(this.ksList[0].department)
      }

      if(this.isLoading || this.ksText === '') return;
      this.isLoading = true;
      let form = {
          st: this.pickDate[0] ? this.pickDate[0] : '',
          et: this.pickDate[1] ? this.pickDate[1] : '',
          ks: this.ksText,
      }

      let url = this.hw_noon_switch === '1' ? getAloneKsTwiceUrl : getAloneKsUrl
      jQuery.ajax({
        url: url,
        type: 'GET',
        data: form,
        success: res => {
          if(res.success){
              this.resetData();
              let data = res.data;
              if(this.hw_noon_switch === '0'){
                this.allData = data;
                if(this.allData.length > 0){
                    this.getNewTableData()
                    this.getTableCol()  // 动态生成表头
                    this.getHandleOver();
                }
              }else if(this.hw_noon_switch === '1'){
                let days = data.days;
                if(days.length > 0){
                  days.forEach(v => {
                    this.allData.push(this.getRowObj(v, 'am'))
                    this.allData.push(this.getRowObj(v, 'pm'))
                  })
                  let obj = {
                    date: '总计',
                    step1_sign: '',
                    step1_uname: '',
                    uname: '',
                    time: '',
                    numTotal: data.sum.sum_num,
                    weightTotal: data.sum.sum_weight,
                    vals: [],
                    wc_sum: data.wc_sum
                  }
                  this.allData.push(obj)
                  this.getNewTableData()
                  this.getTableCol()  // 动态生成表头
                  this.getHandleOver();
                }
              }
              this.postUndoData();
          }
          this.isLoading = false;
        }
      })
    },
    getRowObj(data, key){
      return {
        key: data.day,
        step1_sign: data[key].step1_sign,
        step1_uname: data[key].step1_uname,
        uname: data[key].uname,
        time: data[key].dur,
        vals: data[key].rows.map(v2 => {
          return {
            idwc: v2.idwc,
            time: v2.dur,
            nd: data.day,
            num: v2.sum_num,
            total: v2.sum_weight,
          }
        })
      }
    },
    exportExcel(){
      if(!this.ksText){
        throwErrorTips("请选择科室")
        return
      }
        if(this.isExporting){
            alert('正在进行导出操作，请勿重复点击！')
            return;
        }
        this.isExporting = true;
        let url = '';
        let form = {
          st: this.pickDate[0],
          et: this.pickDate[1],
          ks: this.ksText,
          is_img: 1
        }
        if(this.hw_noon_switch === '1'){
          url = getAloneKsTwiceUrl
          Object.assign(form, {
              need_excel: 1,
          })
        }else{
          url = getAloneKsUrl
          Object.assign(form, {
              export: 1,
              // code: 2
          })
        }
        if(this.$root.$data.is_szy){
          this.downloadExcel(form)
          return
        }
        jQuery.ajax({
          url: url,
          data: form,
          success: res => {
            console.log(res);
            res.success ? window.location = `/oss/down?url=${res.data}` : alert(res.msg)

            this.isExporting = false;
          }
        })
    },
    downloadExcel(form){
      let fileName = this.fileName
      let xhr = new XMLHttpRequest()
      if(this.hw_noon_switch === '1'){
        xhr.open('get', `/w/wastecategory/alone/ks/twice?${qs.stringify(form)}`, true);
      }else {
        xhr.open('get', `/w/wastecategory/alone/ks?${qs.stringify(form)}`, true);
      }
      
      xhr.responseType = 'blob';
      xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
      xhr.onload = function (res) {
        if (this.status == 200) {
          let blob = this.response;
          let a = document.createElement('a');
          let url = window.URL.createObjectURL(blob);
          a.href = url;
          a.download = `${fileName}.xlsx`;
          a.click();

        }
      }
        xhr.send();
      
      this.isExporting = false;
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if(this.hw_noon_switch === '0') return;
      if (columnIndex === 0 && row.date !== '总计') {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }

      if(row.date === '总计'){
        if (columnIndex === 0) {
          return [2, 2];
        } else if (columnIndex === 1) {
          return [0, 0];
        } else if (column.label === '交送人'){
          return [2, 2];
        } else if (column.label === '收运称重'){
          return [0, 0];
        }
      }
    },
  },
}
</script>

<style lang="less">
.el-table thead{
  color: #000;
}
.el-table__footer-wrapper tbody td, .el-table__header-wrapper tbody td{
  background: #fff;
}
.popover-card{
  &.el-popover{
    padding: 0;
  }
  .el-card.is-never-shadow{
    border: 0;
  }
  .footer{
    margin-top: 10px;
  }
}
.month-modal{
  .no-info-tips p{
    line-height: 10px;
  }
  .custom-item{
      display: flex;
      justify-content: space-around;
      align-items: center;
      .info{
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
      }
      img{
          display: inline-block;
          width: 25px;
      }
  }
  .more-icon{
      cursor: pointer;
      border-radius: 50%;
      padding: 2px;
      border: 1px solid #6d6a6a;
      font-size: 16px;
      width: 20px;
      height: 20px;
      line-height: 5px;
      display: block;
      padding-right: 3px;
  }
  .el-table__footer-wrapper{
    .el-table__footer{
      min-height: 50px;
    }
  }
}
.select-ks-dialog {
  &.el-dialog{
    border-radius: 10px;
    width: 450px;
    .el-dialog__body{
        padding: 0px 10px;
    }
    .content{
        height: 500px;
    }
    
    .content{
        padding: 0 20px 10px;
        overflow: hidden;
        height: 100%;
        h3{
            text-align: center;
        }
        .search{
            .el-input{
                width: calc(~'90% - 30px');
            }
        }
        .list{
            overflow-y: scroll;
            height: 430px;
            li{
                font-size: 16px;
                padding: 5px;
                border: 1px solid #EBEEF5;
                margin-bottom: -1px;
                margin-right: 2px;
                position: relative;
            }
        }
        .el-input .el-input__inner{
            position: relative;
            font-size: 14px;
            display: inline-block;
            width: 100%;
        }
        button {
            margin: 5px 5px 5px 0;
            border: 1px solid #ccc;
            padding: 5px 10px;
            border-radius: 5px;
            vertical-align: middle;
            height: 30px;
        }
        .el-icon-circle-check{
            color: green;
            font-size: 22px;
            position: absolute;
            right: 14%;
            top: 18%;
        }
        ::-webkit-scrollbar{
            width: 6px;
            height: 5px;
        }
        ::-webkit-scrollbar-thumb{
            background: #ccc;
            border-radius: 5px;
        }
    }
  }
}
.sign-pic-dialog{
    background: #fff;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 470.4px;
    height: 344.4px;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 10px;
    .el-dialog__header{
        display: none;
    }
    .img-box img{
        width: 100%;
    }
}

.el-table .type-name {
  display: block;
  width: 100%;
  padding: 5px;
  margin: 5px 0;
  border-radius: 5px;
  color: #333;
}
.table-modal{
    width: 80%;
    height: 75%;
    background: #fff;
    border-radius: 6px;
    .el-dialog__header{
      padding: 0;
    }
    .el-dialog__body{
        height: 100%;
        padding-bottom: 50px;
    }
}
.el-dialog .el-table td:first-child {
  border-bottom: 1px solid #ebeef5;
  border: 1px solid #ebeef5;
}
</style>